/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.compiler.support;

import com.aduib.boot.common.SPI.Adaptive;
import com.aduib.boot.common.SPI.FactoryUtils;
import com.aduib.boot.common.SPI.SPI;
import com.aduib.boot.common.SPI.SPIFactory;
import com.aduib.boot.common.SPI.SPILoader;
import com.aduib.boot.common.asm.AsmClassGenerator;
import com.aduib.boot.common.asm.ParameterNameVisitor;
import com.aduib.boot.common.compiler.Compiler;
import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.log.LOG;
import com.aduib.boot.common.util.ClassUtils;
import com.aduib.boot.common.util.IOUtils;
import com.aduib.boot.common.util.StrUtils;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.ASTORE;
import static org.objectweb.asm.Opcodes.ATHROW;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.GOTO;
import static org.objectweb.asm.Opcodes.IFNONNULL;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.RETURN;

/**
 * @description: SPIClassAsmCompiler
 * @author: zzh
 * @date: 2021/10/21 13:39
 */
public class SpiAdaptiveClassAsmCompiler implements Compiler {

  public static final String INSTANCE = "INSTANCE";

  public static final String GET_SPI_METHOD_NAME = "getSPI";

  public static final String EXCEPTION_VOID_STRING_ARG_METHOD = "(Ljava/lang/String;)V";

  public static final String EXCEPTION_VOID_EXCEPTION_ARG_METHOD = "(Ljava/lang/Throwable;)V";

  public static final String INIT_METHOD = "<init>";
  /** 类名后缀 */
  private static final String suffix = "$Adaptive";

  private ParameterNameVisitor parameterNameVisitor;

  private Class<?> interfaceClass;

  public SpiAdaptiveClassAsmCompiler(Class<?> interfaceClass) {
    this.interfaceClass = interfaceClass;
    this.parameterNameVisitor = new ParameterNameVisitor(interfaceClass);
  }

  public SpiAdaptiveClassAsmCompiler() {}

  @Override
  public Class<?> compile(String name, ClassLoader classLoader) {
    if (StrUtils.isNotBlank(name)) {
      this.interfaceClass = ClassUtils.forName(name, classLoader);
      LOG.d("SpiAdaptiveClassAsmCompiler{1}:" + name);
      LOG.d("SpiAdaptiveClassAsmCompiler{2}:" + interfaceClass);
      this.parameterNameVisitor = new ParameterNameVisitor(interfaceClass);
    }
    return doCompile();
  }

  private Class<?> doCompile() {
    AsmClassGenerator builder = new AsmClassGenerator();
    builder.setModifier(Collections.singletonList(AsmClassGenerator.Opcode.OC_PUBLIC));
    builder.setTypeValue(AsmClassGenerator.Opcode.OC_CLASS);
    builder.setClassName(interfaceClass.getName() + suffix);
    // 继承
    Class<?> superclass = interfaceClass.getSuperclass();
    if (superclass != null) {
      builder.setSuperClass(superclass);
    }

    // 实现接口
    builder.addInterface(interfaceClass);

    // 创建构造器
    builder.addConstructorDescriptor(
        new AsmClassGenerator.ConstructorDescriptor(
            Collections.singletonList(AsmClassGenerator.Opcode.OC_PUBLIC)) {
          @Override
          public boolean generate(MethodVisitor mv, boolean enabledCustomize) {
            if (enabledCustomize) {
              mv.visitVarInsn(ALOAD, 0);
              mv.visitFieldInsn(
                  GETSTATIC,
                  Type.getInternalName(SPILoader.class),
                  INSTANCE,
                  Type.getDescriptor(SPIFactory.class));
              mv.visitFieldInsn(
                  PUTFIELD,
                  Type.getInternalName(interfaceClass) + suffix,
                  ClassUtils.getClassName(SPIFactory.class, true),
                  Type.getDescriptor(SPIFactory.class));
            }
            return true;
          }
        });
    // 创建属性
    builder.addFieldDescriptor(
        new AsmClassGenerator.FieldDescriptor(
            ClassUtils.getClassName(SPIFactory.class, true),
            SPIFactory.class,
            Arrays.asList(AsmClassGenerator.Opcode.OC_PUBLIC, AsmClassGenerator.Opcode.OC_FINAL),
            null));
    // 创建方法
    Method[] declaredMethods = interfaceClass.getDeclaredMethods();
    SPI spiAnnotation = interfaceClass.getAnnotation(SPI.class);
    for (Method declaredMethod : declaredMethods) {
      builder.addMethodDescriptor(
          new AsmClassGenerator.MethodDescriptor(
              Arrays.asList(AsmClassGenerator.Opcode.OC_PUBLIC, AsmClassGenerator.Opcode.OC_FINAL),
              declaredMethod.getName(),
              declaredMethod.getReturnType(),
              declaredMethod.getParameterTypes(),
              declaredMethod.getExceptionTypes()) {
            @Override
            public boolean generate(MethodVisitor mv, boolean enabledCustomize) {
              String[] parameterNames = parameterNameVisitor.parameterNames(declaredMethod);
              if (parameterNames != null) {
                for (String parameterName : parameterNames) {
                  mv.visitParameter(parameterName, 0);
                }
              }
              Adaptive adaptiveAnnotation = declaredMethod.getAnnotation(Adaptive.class);
              if (adaptiveAnnotation == null && spiAnnotation == null) {
                // 生成不支持字节码
                return generateUnSupportedExceptionCode(mv, declaredMethod);
              } else {

                String[] methodAdaptiveValue =
                    FactoryUtils.getMethodAdaptiveValue(
                        spiAnnotation, adaptiveAnnotation, interfaceClass);

                generateMethodHeaderCode(mv, declaredMethod);

                generateSpiMethodCode(mv, methodAdaptiveValue, declaredMethod);

                return generateMethodInvokeCode(mv, declaredMethod);
              }
            }

            @Override
            public boolean afterCustomize(MethodVisitor mv, boolean enabledReturn) {
              if (enabledReturn) {
                if (declaredMethod.getReturnType().equals(void.class)
                    || declaredMethod.getReturnType().equals(Void.class)) {
                  mv.visitInsn(RETURN);
                } else if (ClassUtils.isPrimitive(declaredMethod.getReturnType())) {
                  mv.visitInsn(IRETURN);
                } else {
                  mv.visitInsn(ARETURN);
                }
              }
              mv.visitMaxs(3, getParameterTypes().length + 3);
              mv.visitEnd();
              return false;
            }
          });
    }
    try {
      return builder.build();
    } catch (RuntimeException t) {
      throw t;
    } catch (Throwable t) {
      throw new CommonException(
          "Failed to compile class, cause: "
              + t.getMessage()
              + ", class: "
              + interfaceClass
              + "\n, stack: "
              + ClassUtils.stackTraceString(t));
    }
  }

  private boolean generateUnSupportedExceptionCode(MethodVisitor mv, Method declaredMethod) {
    mv.visitTypeInsn(NEW, Type.getInternalName(UnsupportedOperationException.class));
    mv.visitInsn(DUP);
    mv.visitLdcInsn(
        String.format(
            "The method %s of interface %s is not adaptive method!",
            declaredMethod, interfaceClass));
    mv.visitMethodInsn(
        INVOKESPECIAL,
        Type.getInternalName(UnsupportedOperationException.class),
        INIT_METHOD,
        EXCEPTION_VOID_STRING_ARG_METHOD,
        false);
    mv.visitInsn(ATHROW);
    return false;
  }

  private void generateSpiMethodCode(
      MethodVisitor mv, String[] methodAdaptiveValue, Method method) {

    int parameterCount = method.getParameterCount();

    for (String paramName : methodAdaptiveValue) {
      Label label0 = new Label();
      Label label1 = new Label();
      Label label2 = new Label();
      mv.visitTryCatchBlock(label0, label1, label2, Type.getInternalName(Throwable.class));

      Label label5 = new Label();
      mv.visitJumpInsn(IFNONNULL, label5);
      mv.visitLabel(label0);
      mv.visitVarInsn(ALOAD, 0);
      mv.visitFieldInsn(
          GETFIELD,
          Type.getInternalName(interfaceClass) + suffix,
          ClassUtils.getClassName(SPIFactory.class, true),
          Type.getDescriptor(SPIFactory.class));
      mv.visitLdcInsn(Type.getType(Type.getDescriptor(interfaceClass)));
      mv.visitLdcInsn(paramName);
      try {
        String methodDescriptor =
            Type.getMethodDescriptor(
                ClassUtils.getMethod(
                    SPIFactory.class, GET_SPI_METHOD_NAME, Class.class, String.class)
                //                SPIFactory.class.getMethod(GET_SPI_METHOD_NAME, Class.class,
                // String.class)
                );
        mv.visitMethodInsn(
            INVOKEINTERFACE,
            Type.getInternalName(SPIFactory.class),
            GET_SPI_METHOD_NAME,
            methodDescriptor,
            true);
      } catch (CommonException e) {
        throw new CommonException("create adaptive method fail ", e);
      }
      mv.visitTypeInsn(CHECKCAST, Type.getInternalName(interfaceClass));
      mv.visitVarInsn(ASTORE, 1 + parameterCount);
      mv.visitLabel(label1);
      mv.visitJumpInsn(GOTO, label5);
      mv.visitLabel(label2);

      List<String> paramInterNames = new ArrayList<>();
      paramInterNames.add(Type.getInternalName(interfaceClass) + suffix);
      Class<?>[] parameterTypes = method.getParameterTypes();
      if (Objects.nonNull(parameterTypes)) {
        for (Class<?> parameterType : parameterTypes) {
          paramInterNames.add(Type.getInternalName(parameterType));
        }
      }
      paramInterNames.add(Type.getInternalName(interfaceClass));

      mv.visitFrame(
          Opcodes.F_FULL,
          2 + parameterCount,
          paramInterNames.toArray(),
          1,
          new Object[] {Type.getInternalName(Throwable.class)});
      mv.visitVarInsn(ASTORE, 2 + parameterCount);
      mv.visitTypeInsn(NEW, Type.getInternalName(CommonException.class));
      mv.visitInsn(DUP);
      mv.visitVarInsn(ALOAD, 2 + parameterCount);
      mv.visitMethodInsn(
          INVOKESPECIAL,
          Type.getInternalName(CommonException.class),
          INIT_METHOD,
          EXCEPTION_VOID_EXCEPTION_ARG_METHOD,
          false);
      mv.visitInsn(ATHROW);
      mv.visitLabel(label5);
      mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
      mv.visitVarInsn(ALOAD, 1 + parameterCount);
    }
  }

  /**
   * 生成方法代码头部固定行
   *
   * @param mv
   * @param method
   */
  private void generateMethodHeaderCode(MethodVisitor mv, Method method) {
    mv.visitInsn(ACONST_NULL);
    mv.visitVarInsn(ASTORE, 1 + method.getParameterCount());
    mv.visitVarInsn(ALOAD, 1 + method.getParameterCount());
  }

  /**
   * 生成方法执行代码
   *
   * @param mv
   * @param declaredMethod
   */
  private boolean generateMethodInvokeCode(MethodVisitor mv, Method declaredMethod) {
    for (int i = 1; i < declaredMethod.getParameterCount() + 1; i++) {
      mv.visitVarInsn(ALOAD, i);
    }
    mv.visitMethodInsn(
        INVOKEINTERFACE,
        Type.getInternalName(interfaceClass),
        declaredMethod.getName(),
        Type.getMethodDescriptor(declaredMethod),
        true);
    return true;
  }

  /**
   * 生成异常
   *
   * @param mv
   * @param methodAdaptiveValue
   * @return
   */
  @Deprecated
  private List<Label> generateThrowableCode(MethodVisitor mv, String[] methodAdaptiveValue) {
    List<Label> labelList = new ArrayList<Label>();
    for (int i = 0; i < methodAdaptiveValue.length; i++) {
      Label label1 = new Label();
      Label label2 = new Label();
      Label label3 = new Label();
      mv.visitTryCatchBlock(label1, label2, label3, Type.getInternalName(Throwable.class));
      labelList.add(label1);
      labelList.add(label2);
      labelList.add(label3);
    }
    return labelList;
  }

  @Override
  public Class<?> compile(byte[] code, ClassLoader classLoader) {
    return compile(StrUtils.str(code, StandardCharsets.UTF_8), classLoader);
  }

  @Override
  public Class<?> compile(InputStream inputStream, ClassLoader classLoader) {
    return compile(IOUtils.readBytes(inputStream), classLoader);
  }
}
